package com.ruoyi.trigger.job;

import com.ruoyi.task.model.entity.TaskEntity;
import com.ruoyi.task.service.ITaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;

/**
 * TODO
 *
 * @Description
 * @Author wkm
 * @Date 2024/12/27
 **/

@Slf4j
@Component()
public class SendMessageTaskQuartzJob {

    @Resource
    private ITaskService taskService;
    @Resource
    private ThreadPoolTaskExecutor executor;


    @Scheduled(cron = "0/3 * * * * ?")
    public void exec(){
        log.info("Quartz定时任务调度 ");
        try{
            List<TaskEntity> taskEntities = taskService.queryNoSendMessageTaskList();
            if (taskEntities.isEmpty()) return;
            for(TaskEntity taskEntity : taskEntities){
               executor.execute(()->{
                   try {
                       taskService.sendMessage(taskEntity);
                       taskService.updateTaskSendMessageCompleted(taskEntity.getUserId(),taskEntity.getMessageId());
                       log.info("Quartz定时任务,更新任务消息成功 userId :{} topic :{}",taskEntity.getUserId(),taskEntity.getTopic());
                   }catch (Exception e){
                       log.error("Quartz定时任务,更新任务消息失败 userId :{} topic :{}",taskEntity.getUserId(),taskEntity.getTopic());
                       taskService.updateTaskSendMessageFail(taskEntity.getUserId(),taskEntity.getMessageId());
                   }
               });
            }
        }catch (Exception e){
            log.error("定时任务,扫描MQ任务表失败",e);
        }
    }
}
